#!/usr/bin/env bash
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Verify that the package prepared for release is correct.

set -eu

source "$(dirname "$0")/common.sh"
ensure_linux $0
ensure_release_root

this_script="$0"

version=$(cat ".version")
unzipped="unzipped"
packed="packed"
published="published"

rm -rf "$published"
mkdir "$published"

if [ ! -f "$unzipped/.pulled" -o "$version" != "$(cat $unzipped/.pulled)" ]
then
  echo "The originals are not found by $0. Execute 'nest pull' first!" >&2
  exit 1
fi

if [ ! -f "$packed/latest" -o "$version" != "$(cat $packed/latest)" ]
then
  echo "The notes are not found by $0. Execute 'nest pack' first!" >&2
  exit 1
fi

gsutil cp gs://chromedriver/$version/chromedriver_linux64.zip $published/chromedriver_linux64.zip
gsutil cp gs://chromedriver/$version/chromedriver_mac64.zip $published/chromedriver_mac64.zip
gsutil cp gs://chromedriver/$version/chromedriver_mac64_m1.zip $published/chromedriver_mac64_m1.zip
gsutil cp gs://chromedriver/$version/chromedriver_win32.zip $published/chromedriver_win32.zip
gsutil cp gs://chromedriver/$version/notes.txt $published/notes.txt
unzip $published/chromedriver_linux64.zip -d $published/chromedriver_linux64
unzip $published/chromedriver_mac64.zip -d $published/chromedriver_mac64
unzip $published/chromedriver_mac64_m1.zip -d $published/chromedriver_mac64_m1
unzip $published/chromedriver_win32.zip -d $published/chromedriver_win32

function compare_md5 {
  path1="$1"
  path2="$2"
  if [ ! -f "$path1" ]
  then
    echo "File not found by $this_script: $path1" >&2
    exit 1
  fi
  if [ ! -f "$path2" ]
  then
    echo "File not found by $this_script: $path2" >&2
    exit 1
  fi
  s1=$(md5sum -b $path1 | cut -f1 -d' ')
  s2=$(md5sum -b $path2 | cut -f1 -d' ')
  if [ "$s1" != "$s2" ]
  then
    echo "Checksum mismatch between files $path1 and $path2" >&2
    exit 1
  fi
}

compare_md5 "$unzipped/chromedriver_linux64/chromedriver" "$published/chromedriver_linux64/chromedriver"
compare_md5 "$unzipped/chromedriver_mac64/chromedriver" "$published/chromedriver_mac64/chromedriver"
compare_md5 "$unzipped/chromedriver_mac64_m1/chromedriver_mac64/chromedriver" "$published/chromedriver_mac64_m1/chromedriver"
compare_md5 "$unzipped/chromedriver_win32/chromedriver.exe" "$published/chromedriver_win32/chromedriver.exe"
compare_md5 "$packed/notes.txt" "$published/notes.txt"

if ! grep -Eq "ChromeDriver\s+$version" "$published/notes.txt"
then
  echo "Error in $0. Notes file refers to different version than $version in "$published/notes.txt"" >&2
  exit 1
fi
